from app.core.config import settings
from redis.asyncio import Redis
from redis.exceptions import ConnectionError, TimeoutError, AuthenticationError
from loguru import logger


class RedisClient(Redis):
    """
    Redis 客户端
    """

    def __init__(self):
        super(RedisClient, self).__init__(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            password=settings.REDIS_PASSWORD,
            db=settings.REDIS_DB,
            decode_responses=True,
        )

    # 获取 Redis 客户端连接的异步函数
    async def init_redis(self):
        """
        触发初始化连接

        :return:
        """
        try:
            await self.ping()
            logger.info("Redis 连接成功")
        except TimeoutError:
            logger.error("Redis 连接超时")
        except AuthenticationError:
            logger.error("Redis 连接认证失败")
        except ConnectionError as e:
            logger.error("Redis 连接异常 {}", e)

    async def close_redis(self):
        """
        关闭 Redis 客户端连接
        """
        await self.close()
        logger.info("Redis 连接已关闭")


# 初始化 Redis 客户端
redis_client = RedisClient()
